import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import cart from './modules/cart'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    //公共数据
    count:1,
    userinfo:window.localStorage.getItem('userinfo'),
    cartlist:window.localStorage.getItem('cartList'),
    addr:{},
    loadCount:2,
    scrollTop:0
  },
  getters: {
    // getCount(state) {
    //   return state.count + 10
    // },
    getUserInfo(state) {
      if(state.userinfo){
        return JSON.parse(state.userinfo)
      }else{
        return null
      }
    },
    getCartList(state){
      if(state.cartlist){
        return JSON.parse(state.cartlist)
      }else{
        return null
      }
    }

  },
  mutations: {
    // 存储用户信息
    setUserInfo(state,data){
      window.localStorage.setItem('userinfo',JSON.stringify(data))
    },
    setCartList(state,datas){
      // 2021/9/25 获取本地存储数据 yyb
      let cartList = JSON.parse(window.localStorage.getItem('cartList'))

      // 判断本地有没有数据
      if(cartList==null || !cartList.length){
        datas.num = 1
        // 如果没数据就存一份
        window.localStorage.setItem('cartList',JSON.stringify([datas]))
        state.cartlist = window.localStorage.getItem('cartList')
        return
      }

      // 声明变量，判断购物车数据goods_id是否相同
      let hasGoods = false;
      // 遍历购物车数据
      cartList = cartList.map((item,idx) => {
        // 如果数据相同 数量+1
        if(datas.goods_id == item.goods_id){
          datas.num++
          hasGoods = true
        }
        // 返回处理后的数据
        return item
      })
      // 没有找到相同的数据
      if(!hasGoods){
        datas.num = 1
        // 合并数据 并存储到本地
        window.localStorage.setItem('cartList',JSON.stringify([...cartList,datas]))
        state.cartlist = window.localStorage.getItem('cartList')
        return
      }
      // 找到数据 存储本地
      window.localStorage.setItem('cartList',JSON.stringify(cartList))
      state.cartlist = window.localStorage.getItem('cartList')
    },

    setAddr(state,value) {
      state.addr = value
    },
    clearAddr(state) {
      state.addr = {}
    },

    setLoadCount(state){
      state.loadCount--
    },
    initLoadCount(state,num){
      state.loadCount = num
    },
    setScrollTop(state,num){
      state.scrollTop = num
    },
  },
  actions: {
    // setCartList ({commit}) {
    //   commit('setCartList')
    // }
  },
  modules: {
    user,
    cart
  }
})

export default store
